package com.tywj.buscustomerapp.view.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;
import com.tywj.buscustomerapp.Config;
import com.tywj.buscustomerapp.R;
import com.tywj.buscustomerapp.model.bean.BaseReqeust;
import com.tywj.buscustomerapp.model.bean.MonthTicketBean;
import com.tywj.buscustomerapp.model.bean.MyTicketBean;
import com.tywj.buscustomerapp.model.bean.RequestBean;
import com.tywj.buscustomerapp.utils.SPUtils;
import com.tywj.buscustomerapp.utils.SortComparator;
import com.tywj.buscustomerapp.utils.TaylorClickLinstener;
import com.tywj.buscustomerapp.utils.TimeRender;
import com.tywj.buscustomerapp.utils.ToastUtils;
import com.tywj.buscustomerapp.utils.WebServicrUtils;
import com.tywj.buscustomerapp.view.adapter.ViewPagerViewAdapter;
import com.tywj.buscustomerapp.view.myview.LoadingDialog;
import com.tywj.buscustomerapp.view.myview.ToastJoe;
import com.umeng.analytics.MobclickAgent;

import org.json.JSONException;
import org.json.JSONObject;
import org.xmlpull.v1.XmlPullParserException;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Time;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import butterknife.BindView;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class MyTicketActivity extends BaseActivity {

    @BindView(R.id.viewpager) ViewPager viewPager;
    @BindView(R.id.position) TextView positionName;
    @BindView(R.id.error) RelativeLayout errorLayout;
    @BindView(R.id.head_title) TextView title;
    @BindView(R.id.head_left) ImageView back;
    @BindView(R.id.head_right) TextView head_right;
    @BindView(R.id.cancle_ticket) TextView cancelInfo;
    private ViewPagerViewAdapter adapter;
    private List<MyTicketBean> tickets;
    private LoadingDialog waitDialog;
    private AlertDialog build;


    @Override
    protected int getContentId() {
        return R.layout.activity_my_ticket;
    }

    @Override
    protected void initWidget(Bundle savedInstanceState) {
        super.initWidget(savedInstanceState);
        title.setText("我的车票");
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                positionName.setText((position+1)+"/"+tickets.size());
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    @Override
    protected void initData() {
        super.initData();
        Observable.create(new ObservableOnSubscribe<List<MyTicketBean>>() {
            @Override
            public void subscribe(ObservableEmitter<List<MyTicketBean>> e){
                try {
                    List<MyTicketBean> list1 = new ArrayList<>();
                    List<MyTicketBean> list2 = new ArrayList<>();
                    String msg1 = WebServicrUtils.getInstance().getMyTravelMonth(SPUtils.getUserPhone(getApplicationContext()));
                    InputStream in_nocode1 = new ByteArrayInputStream(msg1.getBytes("UTF-8"));
                    List<MonthTicketBean> listM = WebServicrUtils.getInstance().getMyMonthTicket(in_nocode1);
                    if (listM!=null && listM.size()>0){
                        for (int i = 0; i < listM.size(); i++) {
                            if (Integer.valueOf(listM.get(i).getMonth())>=TimeRender.getFullDateStr7() && listM.get(i).getState().equals("待乘车")) {
                                MyTicketBean bean = new MyTicketBean();
                                bean.isMonth = true;
                                bean.setBusNumber(listM.get(i).getBusNumber());
                                bean.setTravelNum(listM.get(i).getLineNumber());
                                bean.setYear(listM.get(i).getYear());
                                bean.setMonth(listM.get(i).getMonth());
                                bean.setMyStart(listM.get(i).getStart());
                                bean.setMyStartTime(listM.get(i).getStartTime());
                                bean.setMyEnd(listM.get(i).getEnd());
                                bean.setMyEndTime(listM.get(i).getEndTime());
                                bean.setState(listM.get(i).getState());
                                bean.setId(listM.get(i).getId());
                                list1.add(bean);
                            }
                        }
                    }
                    String msg = WebServicrUtils.getInstance().getMyTravel(SPUtils.getUserPhone(getApplicationContext()));
                    InputStream in_nocode = new ByteArrayInputStream(msg.getBytes("UTF-8"));
                    List<MyTicketBean> list = WebServicrUtils.getInstance().getMyTicket(in_nocode);
                    if (list!=null && list.size()>0){
                        for (int i = 0; i<list.size(); i++) {
//                            Log.i("tay1",list.get(i).toString());
                            if (list.get(i).getState().equals("待乘车")||list.get(i).getState().equals("已乘车")){
                                if (TimeRender.compareTime2(TimeRender.getFullDateStr(),list.get(i).getBusTime())){
                                    list2.add(list.get(i));
                                }
                            }
                        }
//                        for (int i = list.size()-1; i >=0; i--) {
//                            Log.i("tay1",list.get(i).toString());
//                            if (list.get(i).getState().equals("待乘车")||list.get(i).getState().equals("已乘车")){
//                                if (TimeRender.compareTime2(TimeRender.getFullDateStr(),list.get(i).getBusTime())){
//                                    list2.add(list.get(i));
//                                }
//                            }
//                        }
                        Comparator comp = new SortComparator();
                        Collections.sort(list2,comp);
                        list1.addAll(list2);
                    }
                    if (list1.size()>0) {
                        e.onNext(list1);
                    }else{
                        e.onError(null);
                    }
                } catch (IOException e1) {
                    e1.printStackTrace();
                    e.onError(null);
                } catch (XmlPullParserException e1) {
                    e1.printStackTrace();
                    e.onError(null);
                } catch (Exception e1) {
                    e1.printStackTrace();
                    e.onError(null);
                }
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<List<MyTicketBean>>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        errorLayout.setVisibility(View.VISIBLE);
                        if (waitDialog==null)
                            waitDialog = new LoadingDialog(MyTicketActivity.this);
                        if (!waitDialog.isShowing())
                            waitDialog.show();
                    }
                    @Override
                    public void onNext(List<MyTicketBean> s) {
                        if (waitDialog!=null && waitDialog.isShowing())
                            waitDialog.dismiss();
                        if (s.size()>0 && viewPager!=null) {
                            tickets = s;
                            if (positionName!=null)
                                positionName.setText(1 + "/" + s.size());
                            adapter = new ViewPagerViewAdapter(MyTicketActivity.this, tickets,MyTicketActivity.this);
                            viewPager.setAdapter(adapter);
                            adapter.notifyDataSetChanged();
                            errorLayout.setVisibility(View.GONE);
                            if (getIntent()!=null){
                                int inn = getIntent().getIntExtra("ticketID",0);
                                String id = String.valueOf(inn);
//                                        getIntent().getStringExtra("ticketID");
                                for (int i = 0; i < tickets.size(); i++) {
                                    if (tickets.get(i).getId().equals(id)){
                                        viewPager.setCurrentItem(i);
                                        break;
                                    }
                                }
                            }
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        if(tickets!=null){
                            tickets.clear();
                            adapter.notifyDataSetChanged();
                        }
                        if (waitDialog.isShowing())
                            waitDialog.dismiss();
                    }

                    @Override
                    public void onComplete() {
                        if (waitDialog!=null && waitDialog.isShowing())
                            waitDialog.dismiss();
                    }
                });
    }

    @Override
    protected void initClick() {
        super.initClick();
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        head_right.setOnClickListener(new TaylorClickLinstener() {
            @Override
            public void onMultiClick(View v) {
                if (tickets!=null && tickets.size()>0) {
                    showDialog("退票？", "确定退票？");
                }
            }
        });

        cancelInfo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MyTicketActivity.this,InfoActivity.class);
                intent.putExtra("type",1);
                startActivity(intent);
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(waitDialog!=null){
            waitDialog.dismiss();
        }
        if(build!=null && build.isShowing()){
            build.dismiss();
        }
    }



    /**
     * 退票
     * @param id
     * @param type
     */
    private void doCancleTicket(String id,String type){
        //创建一个请求队列
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        //创建一个请求
        String url = Config.SBURL + "/order/cancelOrder";
        JSONObject object = new JSONObject();
        try {
            object.put("id",id);
            object.put("type",type);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(url, object, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                Log.i("taylor",String.valueOf(jsonObject));
                BaseReqeust data = new Gson().fromJson(String.valueOf(jsonObject),BaseReqeust.class);
                if (data!=null && data.getReCode().equals("201")){
                    ToastJoe.getmToastJoe().ToastShowRight(MyTicketActivity.this,null,"退票成功，钱款将在两个工作日内原路退回");
                    initData();
                }else{
                    ToastJoe.getmToastJoe().ToastLongShow(MyTicketActivity.this, null, "退票失败"+data.getCodeTxt());
                    Log.i("退票",data.toString());
                    if (data.getReCode().equals("301")){
                        ToastJoe.getmToastJoe().ToastLongShow(MyTicketActivity.this, null, data.getCodeTxt());
                    }else {
                        ToastJoe.getmToastJoe().ToastLongShow(MyTicketActivity.this, null, "退票失败");
                    }
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                ToastJoe.getmToastJoe().ToastLongShow(MyTicketActivity.this,null,"退票失败");
            }
        });
        //将创建的请求添加到队列中
        requestQueue.add(jsonObjectRequest);
    }

    private void showDialog(final String title, final String msg){
        build = new AlertDialog.Builder(MyTicketActivity.this,R.style.AlertDialogStyle).create();
        //自定义布局
        final View view = getLayoutInflater().inflate(R.layout.dialog_cancle_layout, null);
        build.setView(view, 0, 0, 0, 0);
        build.show();
        //得到当前显示设备的宽度，单位是像素
        int width = getWindowManager().getDefaultDisplay().getWidth();
        //得到这个dialog界面的参数对象
        WindowManager.LayoutParams params = build.getWindow().getAttributes();
        //设置dialog的界面宽度
        params.width = width-(width/3);
        //设置dialog高度为包裹内容
        params.height =  WindowManager.LayoutParams.WRAP_CONTENT;
        //设置dialog的重心
        params.gravity = Gravity.CENTER;
        build.getWindow().setAttributes(params);
        build.setCanceledOnTouchOutside(true);
        TextView titleTv = view.findViewById(R.id.message);
        TextView messageTv = view.findViewById(R.id.message1);
        titleTv.setText(title);
        messageTv.setText(msg);
        Button btn_sure = view.findViewById(R.id.yes);
        Button btn_cancel = view.findViewById(R.id.no);
        btn_sure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!tickets.get(viewPager.getCurrentItem()).isMonth) {
                    if (tickets.get(viewPager.getCurrentItem()).getState().equals("待乘车")) {
                        doCancleTicket(tickets.get(viewPager.getCurrentItem()).getId(), "0");
                    } else {
                        ToastJoe.getmToastJoe().ToastLongShow(MyTicketActivity.this, null, "当前班次不支持退票");
                    }
                    build.dismiss();
                }else{
                    boolean b1 = Integer.valueOf(TimeRender.getFullDateStr10()[0])<Integer.valueOf(tickets.get(viewPager.getCurrentItem()).getYear());
                    boolean b2 = Integer.valueOf(TimeRender.getFullDateStr10()[1])<Integer.valueOf(tickets.get(viewPager.getCurrentItem()).getMonth());
                    boolean b3 = Integer.valueOf(TimeRender.getFullDateStr10()[0]).equals(Integer.valueOf(tickets.get(viewPager.getCurrentItem()).getYear()));
                    if ((b3 && b2) || b1){
                        doCancleTicket(tickets.get(viewPager.getCurrentItem()).getId(), "1");
                    }else{
                        ToastJoe.getmToastJoe().ToastLongShow(MyTicketActivity.this, null,  TimeRender.getFullDateStr10()[0]+"当前班次不支持退票"+tickets.get(viewPager.getCurrentItem()).getYear());
                    }

                }
            }
        });
        btn_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                build.dismiss();
            }
        });
    }


    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("我的车票");
        MobclickAgent.onResume(this); //统计时长

    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("我的车票");
        MobclickAgent.onPause(this);
    }

}
